<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>JavaScript🌞Ajax | 小李博客</title><meta name="keywords" content="JavaScript"><meta name="author" content="小李博客"><meta name="copyright" content="小李博客"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Ajax Ajax：Asynchronous JavaScript And XML，即异步JavaScript和XML技术。 描述：不是一门新的语言或技术，是由JavaScript、XML、DOM、CSS等多种已有技术组合而成的一种浏览器端技术。 功能：用于实现与服务器进行异步交互的功能。 传统Web工作流程每当用户触发一个页面HTTP请求，就需要服务器返回一个新的页面 Ajax工作流程页面通过A">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaScript🌞Ajax">
<meta property="og:url" content="http://xiaoliblog.cn/page/js01.html">
<meta property="og:site_name" content="小李博客">
<meta property="og:description" content="Ajax Ajax：Asynchronous JavaScript And XML，即异步JavaScript和XML技术。 描述：不是一门新的语言或技术，是由JavaScript、XML、DOM、CSS等多种已有技术组合而成的一种浏览器端技术。 功能：用于实现与服务器进行异步交互的功能。 传统Web工作流程每当用户触发一个页面HTTP请求，就需要服务器返回一个新的页面 Ajax工作流程页面通过A">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/26/527e6ac3b16d4038ba3bd09e3b174450.png">
<meta property="article:published_time" content="2021-01-15T04:25:39.723Z">
<meta property="article:modified_time" content="2021-04-19T13:53:18.004Z">
<meta property="article:author" content="小李博客">
<meta property="article:tag" content="JavaScript">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/26/527e6ac3b16d4038ba3bd09e3b174450.png"><link rel="shortcut icon" href="https://cdn.jsdelivr.net/gh/xiaoliblog/image@6b5e7ef72be1c8973d94e5a9c49accbf775ad820/2021/02/01/c485da031fe0e464d04eaba8a66c4a8f.png"><link rel="canonical" href="http://xiaoliblog.cn/page/js01"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.js" defer></script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: {"appId":"RTG4CPNBLJ","apiKey":"f1745bdad68ceec57653b78244fe332c","indexName":"MyBlogIndex","hits":{"per_page":6},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":100,"languages":{"author":"作者: 小李博客","link":"链接: ","source":"来源: 小李博客","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'mediumZoom',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"top-center"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-04-19 21:53:18'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><link rel="stylesheet" href="/css/MyStyle/MyStyle.css" media="defer" onload="this.media='all'"/><link rel="stylesheet" href="/css/MyStyle/tagStyle.css" media="defer" onload="this.media='all'"/><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/zykjofficial/zykjresource@master/css/font-awesome-animation.min.css" media="defer" onload="this.media='all'"/><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/StaticFile_HEXO@latest/butterfly/css/font-awesome-animation.min.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/StaticFile_HEXO@latest/butterfly/css/plugins.min.css" media="defer" onload="this.media='all'"><meta name="generator" content="Hexo 5.2.0"><link rel="alternate" href="/atom.xml" title="小李博客" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@6b5e7ef72be1c8973d94e5a9c49accbf775ad820/2021/02/01/c485da031fe0e464d04eaba8a66c4a8f.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">210</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">38</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">56</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/box/"><i class="fa-fw fa fa-briefcase"></i><span> 工具箱</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-book"></i><span> 找文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-address-card"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">小李博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/box/"><i class="fa-fw fa fa-briefcase"></i><span> 工具箱</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-book"></i><span> 找文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-address-card"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">JavaScript🌞Ajax</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-01-15T04:25:39.723Z" title="发表于 2021-01-15 12:25:39">2021-01-15</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-04-19T13:53:18.004Z" title="更新于 2021-04-19 21:53:18">2021-04-19</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Web%E5%89%8D%E7%AB%AF/">Web前端</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Web%E5%89%8D%E7%AB%AF/JavaScript/">JavaScript</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.5k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>15分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="JavaScript🌞Ajax"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div><article class="post-content" id="article-container"><h1 id="Ajax"><a href="#Ajax" class="headerlink" title="Ajax"></a>Ajax</h1><ul>
<li>Ajax：Asynchronous JavaScript And XML，即<strong>异步JavaScript和XML技术</strong>。</li>
<li>描述：不是一门新的语言或技术，是由JavaScript、XML、DOM、CSS等多种已有技术组合而成的一种浏览器端技术。</li>
<li>功能：<strong>用于实现与服务器进行异步交互的功能</strong>。</li>
<li>传统Web工作流程<br>每当用户触发一个页面HTTP请求，就需要服务器返回一个新的页面<br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/24/594e68fd5921f40c42a89634c094311c.png"></li>
<li>Ajax工作流程<br>页面通过Ajax对象与服务器进行通信，然后通过DOM操作将返回的结果更新到页面中，整个过程都是在同一个页面中进行的<br>Ajax技术的创新之处在于，改善了传统的“请求-等待-响应-刷新-返回数据”模式，在信息返回之前，用户可以继续自己的操作，当前页面不会因为请求而刷新。这样大大的提高了交互性。</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/24/13af6098b6a7580165ed0f207fc830be.png"></p>
<ul>
<li>相较于传统页面，Ajax技术的优势具体有以下几个方面：<ol>
<li>减轻服务器的负担</li>
<li>节省带宽</li>
<li>用户体验更好</li>
</ol>
</li>
</ul>
<h1 id="PHP服务器"><a href="#PHP服务器" class="headerlink" title="PHP服务器"></a>PHP服务器</h1><ul>
<li>服务器：若需要网页能被互联网中的其它用户访问，就要将网页发布到服务器上，用户通过网址来访问。</li>
<li>常用服务器：PHP、Java、Node.js、ASP.NET等</li>
<li>PHP是一种运行于服务器端的嵌入式脚本编程语言，内置了一个Web服务器。</li>
<li>PHP开发环境搭建：<ol>
<li>下载PHP、vc运行库、补丁（可能）<br>进入官网<a target="_blank" rel="noopener" href="http://php.net/">http://php.net</a>下载PHP7.3.11版本(可以下最新版本)，得到一个压缩包，并解压到指定目录<br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/24/e9e630ef5310e3350faf7c040c6c23d1.png"></li>
<li>创建目录<br>创建”<code>D:\web\php7.3</code>“作为PHP的安装目录，创建”<code>D:\web\htdocs</code>“作为站点目录</li>
<li>启动内置服务器<br>压缩包解压到“D:\web\php7.1”目录下，启动cmd命令行工具，<strong>切换目录到该目录中</strong>，执行以下命令<pre><code>  php -S localhost:8081 -t &quot;D:\web\htdocs&quot;</code></pre>
上述命令中，”-S”用于启动内置Web服务器（S为大写），后面接网络地址和端口号，”-t”用于指定站点目录，此处为”D:\web\htdocs”</li>
<li>常见错误<br>”php“不是内部或外部命令,也不是可运行的程序或批处理文件，这是因为没有配置php的path环境变量。找到php的安装路径(包括压缩包名称)复制新建到path中<br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/24/5463e84058f29b072b863d4561c12f87.png"><br>在cmd命令中php安装目录下下执行<pre><code> php -version</code></pre>
显示版本信息即成功，其他情况可能是8081端口号被占用所造成。</li>
</ol>
</li>
</ul>
<h1 id="Ajax向服务器发送请求"><a href="#Ajax向服务器发送请求" class="headerlink" title="Ajax向服务器发送请求"></a>Ajax向服务器发送请求</h1><ul>
<li>使用Ajax需要通过<code>XMLHttpRequest</code>构造函数创建Ajax对象。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> xhr=<span class="keyword">new</span> XMLHttpRequest();</span><br></pre></td></tr></table></figure>

<ul>
<li>创建完成后就可以使用该对象提供的方法向服务器发送请求。</li>
<li><code>open()</code><br>  open()方法用于创建一个新的HTTP请求，并指定请求方式、请求URL等</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">open(<span class="string">&#x27;method&#x27;</span>,<span class="string">&#x27;URL&#x27;</span>[,asyncFlag[,<span class="string">&#x27;username&#x27;</span>[,<span class="string">&#x27;password&#x27;</span>]]])</span><br><span class="line">method：用于指定请求方式，如GET、POST，不区分大小写。</span><br><span class="line">URL：表示请求的地址。</span><br><span class="line">asyncFlag：可选参数，用于指定请求方式，同步请求为<span class="literal">false</span>，默认为异步请求<span class="literal">true</span>。</span><br><span class="line">userName和password：可选参数，表示HTTP认证的用户名和密码</span><br></pre></td></tr></table></figure>

<blockquote>
<p>同步请求和异步请求的区别在于是否阻塞代码的执行，默认的异步方式是非阻塞的，浏览器端的JS程序不用等待Web服务器的响应，可以继续处理其他事情，而同步则等待Web服务器的响应。</p>
</blockquote>
<ul>
<li><code>send()</code><br>  send()方法用于发送请求到Web服务器并接收响应。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">send(content)</span><br></pre></td></tr></table></figure>

<ul>
<li><code>setRequestHeader()</code><br>  setRequestHeader()方法用于单独指定某个HTTP请求头。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">setRequestHeader(<span class="string">&#x27;header&#x27;</span>,<span class="string">&#x27;value&#x27;</span>);</span><br></pre></td></tr></table></figure>

<h2 id="GET请求"><a href="#GET请求" class="headerlink" title="GET请求"></a>GET请求</h2><ul>
<li><p>Get方式适合从服务器获取数据<br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/24/1b14211b511540f6ef19a042cb403f8c.png"></p>
</li>
<li><p>在PHP服务器的Web站点目录<code>D:\web\htdocs</code>中，创建demo.html文件，编码实现Ajax请求，具体如下</p>
</li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> xhr = <span class="keyword">new</span> XMLHttpRequest();        <span class="comment">//①创建Ajax对象</span></span></span><br><span class="line"><span class="javascript">   <span class="comment">//onreadystatechange：监听Ajax状态变化（Ajax状态发生改变时触发此函数）</span></span></span><br><span class="line"><span class="javascript">   xhr.onreadystatechange = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;  <span class="comment">//④监听</span></span></span><br><span class="line"><span class="javascript">   <span class="comment">//readyState属性：表示Ajax状态，如为XMLHttpRequst.DONE表示此次已完成响应。</span></span></span><br><span class="line"><span class="javascript">   <span class="function"><span class="title">if</span>(<span class="params">xhr.readyState==XMLHttpRequest.DONE</span>)</span>&#123;</span></span><br><span class="line"><span class="javascript">         <span class="function"><span class="title">if</span>(<span class="params">xhr.status==<span class="number">200</span></span>)</span>&#123;</span></span><br><span class="line"><span class="javascript">            <span class="built_in">document</span>.write(xhr.responseText);</span></span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"><span class="javascript">   xhr.open(<span class="string">&#x27;GET&#x27;</span>,<span class="string">&quot;test.php?a=1&amp;b=2&quot;</span>);  <span class="comment">//②打开，建立HTTP连接</span></span></span><br><span class="line"><span class="javascript">   xhr.send();	<span class="comment">//③发送请求</span></span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>和html文件同目录下创建<code>test.php</code>文件，写入以下信息：</li>
</ul>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line"><span class="keyword">echo</span> json_encode($_GET);  <span class="comment">//将URL参数转换为JSON输出</span></span><br></pre></td></tr></table></figure>

<ul>
<li>然后启动PHP服务器后，在浏览器输入<code>http://localhost:8081/demo.html</code> </li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/24/0523753cebb4c82cdb09cfa7eaff7436.png"></p>
<ul>
<li>监听Ajax状态</li>
</ul>
<img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/24/27b7857f2e02fc707559e9fe9d126617.png" width="60%">

<h3 id="处理服务器返回的信息"><a href="#处理服务器返回的信息" class="headerlink" title="处理服务器返回的信息"></a>处理服务器返回的信息</h3><ul>
<li><code>readyState</code>属性<br>  readyState属性用于获取Ajax的当前状态，状态值有5种形式。</li>
</ul>
<table>
<thead>
<tr>
<th align="center">状态值</th>
<th align="center">XMLHttpRequest静态属性名</th>
<th align="center">说明</th>
<th align="center">解释</th>
</tr>
</thead>
<tbody><tr>
<td align="center">0</td>
<td align="center">UNSET</td>
<td align="center">未发送</td>
<td align="center">对象已创建</td>
</tr>
<tr>
<td align="center">1</td>
<td align="center">OPENED</td>
<td align="center">已打开</td>
<td align="center">open()方法已调用</td>
</tr>
<tr>
<td align="center">2</td>
<td align="center">HEADERS_RECEIVED</td>
<td align="center">收到响应头</td>
<td align="center">send()方法已调用</td>
</tr>
<tr>
<td align="center">3</td>
<td align="center">LOADING</td>
<td align="center">数据传送中</td>
<td align="center">响应体部分正在被接收</td>
</tr>
<tr>
<td align="center">4</td>
<td align="center">DONE</td>
<td align="center">完成</td>
<td align="center">数据接收完</td>
</tr>
</tbody></table>
<ul>
<li><code>onreadystatechange</code>属性<br>  onreadystatechange事件属性用于感知readyState属性状态的改变，当readyState状态发送改变时，就会调用此事件。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">   <span class="keyword">var</span> xhr=<span class="keyword">new</span> XMLHttpRequest();</span><br><span class="line">   xhr.onreadystatechange=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(xhr.readyState);</span><br><span class="line">   &#125;;</span><br><span class="line">   <span class="built_in">console</span>.log(xhr.readyState);</span><br><span class="line">   xhr.open(<span class="string">&#x27;GET&#x27;</span>,<span class="string">&#x27;test.php&#x27;</span>);</span><br><span class="line">   xhr.send(); </span><br><span class="line">&lt;/script&gt;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">0</span></span><br><span class="line"><span class="comment">1</span></span><br><span class="line"><span class="comment">2</span></span><br><span class="line"><span class="comment">3</span></span><br><span class="line"><span class="comment">4</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<ul>
<li><p>可以看到readyState属性值初始值为0，当调用<code>open()</code>和<code>send()</code>方法后，readyState属性的值会发生变化，每次变化都会触发onreadystatechange事件。</p>
</li>
<li><p><code>status</code>属性<br>  status属性用于返回当前请求的HTTP状态码，值为数值类型</p>
</li>
</ul>
<table>
<thead>
<tr>
<th align="center">状态码</th>
<th align="center">含义</th>
<th align="center">状态码</th>
<th align="center">含义</th>
</tr>
</thead>
<tbody><tr>
<td align="center">200</td>
<td align="center">正常</td>
<td align="center">403</td>
<td align="center">禁止</td>
</tr>
<tr>
<td align="center">301</td>
<td align="center">永久移动</td>
<td align="center">404</td>
<td align="center">找不到</td>
</tr>
<tr>
<td align="center">302</td>
<td align="center">临时移动</td>
<td align="center">500</td>
<td align="center">内部服务器错误</td>
</tr>
<tr>
<td align="center">304</td>
<td align="center">未修改</td>
<td align="center">502</td>
<td align="center">无效网关</td>
</tr>
<tr>
<td align="center">401</td>
<td align="center">未经授权</td>
<td align="center">504</td>
<td align="center">网关超时</td>
</tr>
</tbody></table>
<ul>
<li><strong>获取响应信息的相关属性</strong></li>
</ul>
<table>
<thead>
<tr>
<th align="center">属性名</th>
<th align="center">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>responseText</code></td>
<td align="center">将响应信息作为字符串返回</td>
</tr>
<tr>
<td align="center"><code>responseXML</code></td>
<td align="center">将响应信息格式为XML Document对象并返回(只读)</td>
</tr>
</tbody></table>
<ul>
<li><strong>服务端代码简介</strong></li>
</ul>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line"><span class="keyword">echo</span> json_encode($_GET);  <span class="comment">//将URL参数转换为JSON输出</span></span><br></pre></td></tr></table></figure>

<ul>
<li><code>$_GET</code>：GET方式提交到服务器端的数据(必须大写)</li>
<li><code>json_encode</code>：将参数转换为json格式</li>
<li><code>echo</code>：输出，返回给客户端</li>
</ul>
<h2 id="Post请求"><a href="#Post请求" class="headerlink" title="Post请求"></a>Post请求</h2><ul>
<li><code>Post</code>方式适合向服务器发送数据</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/24/d29da1c5cf33939f7d3d2f50ef6f3e9f.png"></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"> <span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> xhr = <span class="keyword">new</span> XMLHttpRequest();</span></span><br><span class="line"><span class="javascript">   xhr.onreadystatechange = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span></span><br><span class="line"><span class="javascript">      <span class="function"><span class="title">if</span>(<span class="params">xhr.readyState==XMLHttpRequest.DONE</span>)</span>&#123;</span></span><br><span class="line"><span class="javascript">         <span class="function"><span class="title">if</span>(<span class="params">xhr.status==<span class="number">200</span></span>)</span>&#123;</span></span><br><span class="line"><span class="javascript">               <span class="built_in">document</span>.write(xhr.responseText);</span></span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"><span class="javascript">   xhr.open(<span class="string">&#x27;POST&#x27;</span>,<span class="string">&#x27;test.php&#x27;</span>);</span></span><br><span class="line"><span class="javascript">   <span class="comment">//在HTTP请求头中指定实体内容的编码格式</span></span></span><br><span class="line"><span class="javascript">   xhr.setRequestHeader(<span class="string">&#x27;Content-type&#x27;</span>,<span class="string">&#x27;application/x-www-form-urlencoded&#x27;</span>);</span></span><br><span class="line"><span class="javascript">   <span class="comment">// xhr.send(&#x27;name=Lily&amp;age=18&#x27;);</span></span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> name = <span class="string">&#x27;Lily&#x27;</span>;</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> age = <span class="number">18</span>;</span></span><br><span class="line"><span class="javascript">   xhr.send(<span class="string">&#x27;name=&#x27;</span> + name + <span class="string">&#x27;&amp;age=&#x27;</span> + age);</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line"><span class="keyword">echo</span> json_encode($_POST);</span><br></pre></td></tr></table></figure>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/24/4b86a86cd1d2681938bb6c9c9e575f8b.png"></p>
<ul>
<li>通过POST方式向服务器发送ajax请求须设置请求头字段，且在open方法后调用</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Content-Type：application/x-www-form-urlencoded</span><br></pre></td></tr></table></figure>

<ul>
<li>拓展阅读<br><a target="_blank" rel="noopener" href="https://www.cnblogs.com/qlhMeiMei/p/6846392.html">https://www.cnblogs.com/qlhMeiMei/p/6846392.html</a></li>
<li>如果需要传递特殊字符时，可以使用<code>encodeURIComponent()</code>进行URL编码</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> url=<span class="string">&#x27;http://xxx/test.php?name=&#x27;</span>+<span class="built_in">encodeURIComponent</span>(<span class="string">&#x27;A&amp;B C&#x27;</span>);;</span><br><span class="line"><span class="built_in">console</span>.log(url);<span class="comment">//结果输出：http://xxx/test.php?name=A%26B%20C</span></span><br></pre></td></tr></table></figure>

<ul>
<li>在经过URL编码后，”&amp;”被转化为”%26”，空格被转换为”%20”，当服务器收到已编码的内容之后，会对其进行解码，从而正确识别。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> str=<span class="string">&#x27;A%26B%20C&#x27;</span>;</span><br><span class="line"><span class="built_in">console</span>.log(<span class="built_in">encodeURIComponent</span>(str)); <span class="comment">//输出结果：A&amp;B C</span></span><br></pre></td></tr></table></figure>

<h1 id="数据交换格式"><a href="#数据交换格式" class="headerlink" title="数据交换格式"></a>数据交换格式</h1><ul>
<li>XML</li>
<li>JSON<br>JSON是一种轻量级的数据交换格式，它采用完全独立于语言的文本格式。</li>
</ul>
<img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/24/7193183d914eb22d6ade0fab7baeda89.png" width="60%">

<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> obj = &#123;<span class="attr">name</span>:<span class="string">&#x27;Tom&#x27;</span>,<span class="attr">age</span>:<span class="number">24</span>&#125;;</span></span><br><span class="line"><span class="javascript">   <span class="comment">//stringify：将对象转换为JSON字符串</span></span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> json = <span class="built_in">JSON</span>.stringify(obj);</span></span><br><span class="line"><span class="javascript">   <span class="keyword">var</span> xhr = <span class="keyword">new</span> XMLHttpRequest();</span></span><br><span class="line"><span class="javascript">   xhr.onreadystatechange = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span></span><br><span class="line"><span class="javascript">      <span class="function"><span class="title">if</span>(<span class="params">xhr.readyState==XMLHttpRequest.DONE</span>)</span>&#123;</span></span><br><span class="line"><span class="javascript">         <span class="function"><span class="title">if</span>(<span class="params">xhr.status==<span class="number">200</span></span>)</span>&#123;</span></span><br><span class="line"><span class="javascript">            <span class="comment">// var json_res = xhr.responseText;</span></span></span><br><span class="line"><span class="javascript">            <span class="comment">//JSON.parse：将JSON字符串转换成JS对象。</span></span></span><br><span class="line"><span class="javascript">            <span class="comment">// var obj_res = JSON.parse(json_res);</span></span></span><br><span class="line"><span class="javascript">            <span class="comment">//obj.name：JSON对象的成员。</span></span></span><br><span class="line"><span class="javascript">            <span class="comment">// document.write(obj_res.name);</span></span></span><br><span class="line"><span class="javascript">            <span class="built_in">document</span>.write(xhr.responseText);</span></span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"><span class="javascript">   xhr.open(<span class="string">&#x27;post&#x27;</span>,<span class="string">&#x27;test.php&#x27;</span>);</span></span><br><span class="line"><span class="javascript">   xhr.setRequestHeader(<span class="string">&#x27;Content-type&#x27;</span>,<span class="string">&#x27;application/x-www-form-urlencoded&#x27;</span>);</span></span><br><span class="line"><span class="javascript">   xhr.send(<span class="string">&#x27;msg=&#x27;</span> + <span class="built_in">encodeURIComponent</span>(json));</span></span><br><span class="line"><span class="javascript">   <span class="comment">//encodeURIComponet：对字符串进行URI编码</span></span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>

<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line"> <span class="keyword">echo</span> $_POST[<span class="string">&#x27;msg&#x27;</span>];</span><br></pre></td></tr></table></figure>

<p> <img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/24/04d7091a2a8d37f98eb4611d5fcdc164.png"></p>
<h1 id="无刷新分页"><a href="#无刷新分页" class="headerlink" title="无刷新分页"></a>无刷新分页</h1><ul>
<li>代码思路<ol>
<li>首先读取第一页（客户端提交1，服务端返回第1页内容的json数据）；</li>
<li>根据点击的按钮，读取相应页。</li>
</ol>
</li>
<li>自调用函数<br>用<code>()</code>包裹匿名函数，其后的（）表示给匿名函数传递参数并立即执行，完成函数的自调用。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//自调用函数：</span></span><br><span class="line">( <span class="function"><span class="keyword">function</span>  函数名(<span class="params"></span>)</span>&#123;</span><br><span class="line">   代码;</span><br><span class="line">&#125;) ( )；</span><br></pre></td></tr></table></figure>

<ul>
<li>回调函数<br>若想要函数体中某部分功能由调用者决定，此时可以使用回调函数。<br>简单说，在一个函数执行完毕后，得到想要的特定数据后再去执行的函数，即为回调函数。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//定义函数</span></span><br><span class="line">   <span class="function"><span class="keyword">function</span> <span class="title">f1</span>(<span class="params">f2,f3</span>)</span>&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">&quot;11111&quot;</span>);</span><br><span class="line">      f2();</span><br><span class="line">      f3();</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">&quot;22222&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"><span class="comment">//调用函数</span></span><br><span class="line">   f1(</span><br><span class="line">      <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">&quot;33333&quot;</span>);</span><br><span class="line">   &#125;,</span><br><span class="line">      <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">&quot;44444&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">);</span><br><span class="line"><span class="comment">//运行结果</span></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">11111</span></span><br><span class="line"><span class="comment">33333</span></span><br><span class="line"><span class="comment">44444</span></span><br><span class="line"><span class="comment">22222</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<ul>
<li> 继承</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//构造函数</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params">name</span>)</span>&#123;</span><br><span class="line">   <span class="built_in">this</span>.name=name;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//利用原型对象实现继承</span></span><br><span class="line">Person.prototype.sayHello=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">   <span class="built_in">console</span>.log(<span class="string">&quot;你好，我是&quot;</span>+<span class="built_in">this</span>.name);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> p1=<span class="keyword">new</span> Person(<span class="string">&#x27;Jim&#x27;</span>);</span><br><span class="line">p1.sayHello();</span><br></pre></td></tr></table></figure>

<ul>
<li>源码解析<ol>
<li>构造函数PageList：封装页面信息，并添加点击事件实现与用户的交互。</li>
<li>构造函数Comment：向服务器发送ajax请求，获取评论内容，并将服务器返回的JSON数据放入页面中显示出来。</li>
<li>源码解析–PageList：封装页面信息，并添加点击事件实现与用户的交互。</li>
<li>页面信息：<br>   页面元素：首页、尾页、上一页、下一页、页码<pre><code>   数据（变量）：页码、总共页数</code></pre>
</li>
<li>点击事件：<br>  为四个页面元素添加onclick事件，以更新页面内容。</li>
<li>函       数:<br> 根据页码更新页面内容。</li>
</ol>
</li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span> <span class="meta-keyword">PUBLIC</span> <span class="meta-string">&quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot;</span> <span class="meta-string">&quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">xmlns</span>=<span class="string">&quot;http://www.w3.org/1999/xhtml&quot;</span> <span class="attr">xml:lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;Content-Type&quot;</span> <span class="attr">content</span>=<span class="string">&quot;text/html;charset=UTF-8&quot;</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">style</span>&gt;</span></span><br><span class="line"><span class="css">      <span class="selector-tag">body</span>&#123;<span class="attribute">background</span>:<span class="number">#eee</span>;<span class="attribute">margin</span>:<span class="number">0</span>&#125;</span></span><br><span class="line"><span class="css">      <span class="selector-class">.box</span>&#123;<span class="attribute">width</span>:<span class="number">800px</span>;<span class="attribute">margin</span>:<span class="number">0</span> auto;<span class="attribute">background</span>:<span class="number">#fefefe</span>;<span class="attribute">border-radius</span>:<span class="number">8px</span>;<span class="attribute">padding</span>:<span class="number">20px</span>;<span class="attribute">box-sizing</span>:border-box;<span class="attribute">margin-top</span>:<span class="number">40px</span>&#125;</span></span><br><span class="line"><span class="css">      <span class="selector-class">.title</span>&#123;<span class="attribute">font-family</span>:<span class="string">&#x27;Microsoft YaHei&#x27;</span>;<span class="attribute">color</span>:<span class="number">#666</span>;<span class="attribute">font-size</span>:<span class="number">24px</span>;<span class="attribute">text-align</span>:center;<span class="attribute">margin</span>:<span class="number">10px</span> <span class="number">0</span>&#125;</span></span><br><span class="line"><span class="css">      <span class="selector-class">.comment</span> <span class="selector-tag">ul</span>&#123;<span class="attribute">margin</span>:<span class="number">0</span>;<span class="attribute">padding</span>:<span class="number">10px</span>;<span class="attribute">list-style</span>:none;<span class="attribute">border-bottom</span>:<span class="number">1px</span> solid <span class="number">#ccc</span>&#125;</span></span><br><span class="line"><span class="css">      <span class="selector-class">.comment</span> <span class="selector-tag">li</span>&#123;<span class="attribute">line-height</span>:<span class="number">32px</span>&#125;</span></span><br><span class="line"><span class="css">      <span class="selector-class">.pagelist</span>&#123;<span class="attribute">margin-top</span>:<span class="number">20px</span>;<span class="attribute">text-align</span>:center&#125;</span></span><br><span class="line"><span class="css">      <span class="selector-class">.pagelist</span> <span class="selector-tag">span</span>&#123;<span class="attribute">margin</span>:<span class="number">0</span> <span class="number">2px</span>&#125;</span></span><br><span class="line"><span class="css">      <span class="selector-class">.pagelist</span> <span class="selector-tag">button</span>&#123;<span class="attribute">padding</span>:<span class="number">6px</span> <span class="number">10px</span>;<span class="attribute">cursor</span>:pointer&#125;</span></span><br><span class="line"><span class="css">      <span class="selector-class">.pagelist</span> <span class="selector-tag">button</span><span class="selector-pseudo">:disabled</span>&#123;<span class="attribute">cursor</span>:default&#125;</span></span><br><span class="line"><span class="css">      <span class="selector-class">.progress</span> <span class="selector-tag">div</span>&#123;<span class="attribute">width</span>:<span class="number">0%</span>;<span class="attribute">height</span>:<span class="number">1px</span>;<span class="attribute">position</span>:fixed;<span class="attribute">top</span>:<span class="number">0</span>;<span class="attribute">background-color</span>:<span class="number">#38f</span>;<span class="attribute">box-shadow</span>:<span class="number">1px</span> <span class="number">1px</span> <span class="number">1px</span> <span class="number">#6bf</span>;<span class="attribute">transition</span>: all <span class="number">0.8s</span>&#125;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;progress&quot;</span> <span class="attr">class</span>=<span class="string">&quot;progress&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;box&quot;</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;title&quot;</span>&gt;</span>查看商品评论<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;comment&quot;</span> <span class="attr">class</span>=<span class="string">&quot;comment&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;pagelist&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">p</span>&gt;</span>当前是第<span class="tag">&lt;<span class="name">span</span> <span class="attr">id</span>=<span class="string">&quot;page_num&quot;</span>&gt;</span>1<span class="tag">&lt;/<span class="name">span</span>&gt;</span>页<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">button</span> <span class="attr">id</span>=<span class="string">&quot;page_first&quot;</span>&gt;</span>首页<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">button</span> <span class="attr">id</span>=<span class="string">&quot;page_prev&quot;</span>&gt;</span>上一页<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">button</span> <span class="attr">id</span>=<span class="string">&quot;page_next&quot;</span>&gt;</span>下一页<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">button</span> <span class="attr">id</span>=<span class="string">&quot;page_last&quot;</span>&gt;</span>尾页<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">        (<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span></span><br><span class="line"><span class="javascript">            <span class="function"><span class="keyword">function</span> <span class="title">PageList</span>(<span class="params">options</span>)</span>&#123;</span></span><br><span class="line"><span class="javascript">                <span class="keyword">for</span> (<span class="keyword">var</span> i <span class="keyword">in</span> options) &#123;</span></span><br><span class="line"><span class="javascript">                    <span class="built_in">this</span>[i] = options[i];</span></span><br><span class="line">                &#125;</span><br><span class="line"><span class="javascript">                <span class="keyword">var</span> obj = <span class="built_in">this</span>;</span></span><br><span class="line"><span class="javascript">                <span class="built_in">this</span>.first.onclick = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span></span><br><span class="line">                    obj.page = 1;</span><br><span class="line">                    obj.onChange();</span><br><span class="line">                &#125;;</span><br><span class="line"><span class="javascript">                <span class="built_in">this</span>.prev.onclick = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span></span><br><span class="line">                    obj.page = (obj.page &gt; 1) ? (obj.page - 1) : 1;</span><br><span class="line">                    obj.onChange();</span><br><span class="line">                &#125;;</span><br><span class="line"><span class="javascript">                <span class="built_in">this</span>.next.onclick = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span></span><br><span class="line">                    obj.page = (obj.page &gt;= obj.maxPage) ? obj.maxPage : (obj.page + 1);</span><br><span class="line">                    obj.onChange();</span><br><span class="line">                &#125;;</span><br><span class="line"><span class="javascript">                <span class="built_in">this</span>.last.onclick = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span></span><br><span class="line">                    obj.page = obj.maxPage;</span><br><span class="line">                    obj.onChange();</span><br><span class="line">                &#125;;</span><br><span class="line">            &#125;</span><br><span class="line"><span class="javascript">            <span class="function"><span class="keyword">function</span> <span class="title">Comment</span>(<span class="params">obj</span>)</span>&#123;</span></span><br><span class="line"><span class="javascript">                <span class="built_in">this</span>.obj = obj;</span></span><br><span class="line">            &#125;</span><br><span class="line"><span class="javascript">            Comment.prototype.ajax = <span class="function"><span class="keyword">function</span>(<span class="params">url, start, complete</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">          <span class="keyword">var</span> xhr = <span class="keyword">new</span> XMLHttpRequest();</span></span><br><span class="line"><span class="javascript">          xhr.onreadystatechange = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span></span><br><span class="line">            if (xhr.readyState === 4) &#123;</span><br><span class="line"><span class="handlebars"><span class="xml">              if (xhr.status <span class="tag">&lt; <span class="attr">200</span> || <span class="attr">xhr.status</span> &gt;</span>= 300 &amp;&amp; xhr.status !== 304) &#123;</span></span></span><br><span class="line"><span class="javascript">                alert(<span class="string">&#x27;服务器异常&#x27;</span>);</span></span><br><span class="line"><span class="javascript">                <span class="keyword">return</span>;</span></span><br><span class="line">              &#125;</span><br><span class="line"><span class="javascript">              <span class="keyword">try</span> &#123;</span></span><br><span class="line"><span class="javascript">                <span class="keyword">var</span> json = <span class="built_in">JSON</span>.parse(xhr.responseText);</span></span><br><span class="line"><span class="javascript">              &#125; <span class="function"><span class="title">catch</span>(<span class="params">e</span>)</span> &#123;</span></span><br><span class="line"><span class="javascript">                alert(<span class="string">&#x27;解析服务器返回信息失败&#x27;</span>);</span></span><br><span class="line"><span class="javascript">                <span class="keyword">return</span>;</span></span><br><span class="line">              &#125;</span><br><span class="line">              complete(json);</span><br><span class="line">            &#125;</span><br><span class="line">          &#125;;</span><br><span class="line"><span class="javascript">          xhr.open(<span class="string">&#x27;GET&#x27;</span>, url);</span></span><br><span class="line">          xhr.send();</span><br><span class="line">          start();</span><br><span class="line">        &#125;;</span><br><span class="line"><span class="javascript">         Comment.prototype.create = <span class="function"><span class="keyword">function</span>(<span class="params">data</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">          <span class="keyword">var</span> html = <span class="string">&#x27;&#x27;</span>;</span></span><br><span class="line"><span class="javascript">          <span class="keyword">for</span> (<span class="keyword">var</span> i <span class="keyword">in</span> data) &#123;</span></span><br><span class="line"><span class="javascript">            html += <span class="string">&#x27;&lt;ul&gt;&lt;li&gt;用户名：&#x27;</span> + data[i].user + <span class="string">&#x27;　发表时间：&#x27;</span> + data[i].time + <span class="string">&#x27;&lt;/li&gt;&#x27;</span>;</span></span><br><span class="line"><span class="handlebars"><span class="xml">            html += &#x27;<span class="tag">&lt;<span class="name">li</span>&gt;</span>&#x27; + data[i].content + &#x27;<span class="tag">&lt;/<span class="name">li</span>&gt;</span><span class="tag">&lt;/<span class="name">ul</span>&gt;</span>&#x27;;</span></span></span><br><span class="line">          &#125;</span><br><span class="line"><span class="javascript">          <span class="built_in">this</span>.obj.innerHTML = html;</span></span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line"><span class="javascript">           <span class="keyword">var</span> comment = <span class="keyword">new</span> Comment(<span class="built_in">document</span>.getElementById(<span class="string">&#x27;comment&#x27;</span>));</span></span><br><span class="line"></span><br><span class="line"><span class="javascript">            <span class="keyword">var</span> pageList =<span class="keyword">new</span> PageList(&#123;</span></span><br><span class="line">                page: 1,</span><br><span class="line">                maxPage: 1,</span><br><span class="line"><span class="javascript">                first: <span class="built_in">document</span>.getElementById(<span class="string">&#x27;page_first&#x27;</span>),</span></span><br><span class="line"><span class="javascript">                prev: <span class="built_in">document</span>.getElementById(<span class="string">&#x27;page_prev&#x27;</span>),</span></span><br><span class="line"><span class="javascript">                next: <span class="built_in">document</span>.getElementById(<span class="string">&#x27;page_next&#x27;</span>),</span></span><br><span class="line"><span class="javascript">                last: <span class="built_in">document</span>.getElementById(<span class="string">&#x27;page_last&#x27;</span>),</span></span><br><span class="line"><span class="javascript">                pageNum: <span class="built_in">document</span>.getElementById(<span class="string">&#x27;page_num&#x27;</span>),</span></span><br><span class="line"><span class="javascript">                onChange:<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span></span><br><span class="line"><span class="javascript">                    comment.ajax(<span class="string">&#x27;data.php?page=&#x27;</span> + <span class="built_in">this</span>.page,</span></span><br><span class="line"><span class="javascript">                        <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;<span class="comment">//start回调函数</span></span></span><br><span class="line"></span><br><span class="line">                        &#125;,</span><br><span class="line"><span class="javascript">                        <span class="function"><span class="keyword">function</span>(<span class="params">json</span>)</span>&#123; <span class="comment">//complete回调函数</span></span></span><br><span class="line">                            pageList.maxPage = json.maxPage;</span><br><span class="line">                            comment.create(json.data);</span><br><span class="line">                        &#125;</span><br><span class="line">                    )</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">            pageList.onChange();</span><br><span class="line">        &#125;)();</span><br><span class="line">    <span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line"><span class="comment">//定义data数组，包含10个元素，每个元素表示1条评论</span></span><br><span class="line">$data = [</span><br><span class="line">    [<span class="string">&#x27;id&#x27;</span> =&gt; <span class="number">1</span>, <span class="string">&#x27;user&#x27;</span> =&gt; <span class="string">&#x27;test&#x27;</span>, <span class="string">&#x27;time&#x27;</span> =&gt; <span class="string">&#x27;2018-01-01&#x27;</span>, <span class="string">&#x27;content&#x27;</span> =&gt; <span class="string">&#x27;评论111&#x27;</span>],</span><br><span class="line">    [<span class="string">&#x27;id&#x27;</span> =&gt; <span class="number">2</span>, <span class="string">&#x27;user&#x27;</span> =&gt; <span class="string">&#x27;test&#x27;</span>, <span class="string">&#x27;time&#x27;</span> =&gt; <span class="string">&#x27;2018-01-01&#x27;</span>, <span class="string">&#x27;content&#x27;</span> =&gt; <span class="string">&#x27;评论222&#x27;</span>],</span><br><span class="line">    [<span class="string">&#x27;id&#x27;</span> =&gt; <span class="number">3</span>, <span class="string">&#x27;user&#x27;</span> =&gt; <span class="string">&#x27;test&#x27;</span>, <span class="string">&#x27;time&#x27;</span> =&gt; <span class="string">&#x27;2018-01-01&#x27;</span>, <span class="string">&#x27;content&#x27;</span> =&gt; <span class="string">&#x27;评论233&#x27;</span>],</span><br><span class="line">    [<span class="string">&#x27;id&#x27;</span> =&gt; <span class="number">4</span>, <span class="string">&#x27;user&#x27;</span> =&gt; <span class="string">&#x27;test&#x27;</span>, <span class="string">&#x27;time&#x27;</span> =&gt; <span class="string">&#x27;2018-01-01&#x27;</span>, <span class="string">&#x27;content&#x27;</span> =&gt; <span class="string">&#x27;评论444&#x27;</span>],</span><br><span class="line">    [<span class="string">&#x27;id&#x27;</span> =&gt; <span class="number">5</span>, <span class="string">&#x27;user&#x27;</span> =&gt; <span class="string">&#x27;test&#x27;</span>, <span class="string">&#x27;time&#x27;</span> =&gt; <span class="string">&#x27;2018-01-01&#x27;</span>, <span class="string">&#x27;content&#x27;</span> =&gt; <span class="string">&#x27;评论555&#x27;</span>],</span><br><span class="line">    [<span class="string">&#x27;id&#x27;</span> =&gt; <span class="number">6</span>, <span class="string">&#x27;user&#x27;</span> =&gt; <span class="string">&#x27;test&#x27;</span>, <span class="string">&#x27;time&#x27;</span> =&gt; <span class="string">&#x27;2018-01-01&#x27;</span>, <span class="string">&#x27;content&#x27;</span> =&gt; <span class="string">&#x27;评论666&#x27;</span>],</span><br><span class="line">    [<span class="string">&#x27;id&#x27;</span> =&gt; <span class="number">7</span>, <span class="string">&#x27;user&#x27;</span> =&gt; <span class="string">&#x27;test&#x27;</span>, <span class="string">&#x27;time&#x27;</span> =&gt; <span class="string">&#x27;2018-01-01&#x27;</span>, <span class="string">&#x27;content&#x27;</span> =&gt; <span class="string">&#x27;评论777&#x27;</span>],</span><br><span class="line">    [<span class="string">&#x27;id&#x27;</span> =&gt; <span class="number">8</span>, <span class="string">&#x27;user&#x27;</span> =&gt; <span class="string">&#x27;test&#x27;</span>, <span class="string">&#x27;time&#x27;</span> =&gt; <span class="string">&#x27;2018-01-01&#x27;</span>, <span class="string">&#x27;content&#x27;</span> =&gt; <span class="string">&#x27;评论888&#x27;</span>],</span><br><span class="line">    [<span class="string">&#x27;id&#x27;</span> =&gt; <span class="number">9</span>, <span class="string">&#x27;user&#x27;</span> =&gt; <span class="string">&#x27;test&#x27;</span>, <span class="string">&#x27;time&#x27;</span> =&gt; <span class="string">&#x27;2018-01-01&#x27;</span>, <span class="string">&#x27;content&#x27;</span> =&gt; <span class="string">&#x27;评论999&#x27;</span>],</span><br><span class="line">    [<span class="string">&#x27;id&#x27;</span> =&gt; <span class="number">10</span>, <span class="string">&#x27;user&#x27;</span> =&gt; <span class="string">&#x27;test&#x27;</span>, <span class="string">&#x27;time&#x27;</span> =&gt; <span class="string">&#x27;2018-01-01&#x27;</span>, <span class="string">&#x27;content&#x27;</span> =&gt; <span class="string">&#x27;评论1010&#x27;</span>],</span><br><span class="line">];</span><br><span class="line">$page = <span class="keyword">isset</span>($_GET[<span class="string">&#x27;page&#x27;</span>]) ? max((<span class="keyword">int</span>)$_GET[<span class="string">&#x27;page&#x27;</span>], <span class="number">1</span>) : <span class="number">1</span>;</span><br><span class="line">$size = <span class="number">2</span>;</span><br><span class="line">$maxPage = ceil(count($data) / $size);</span><br><span class="line"><span class="keyword">echo</span> json_encode([</span><br><span class="line">    <span class="string">&#x27;data&#x27;</span> =&gt; array_slice($data, ($page - <span class="number">1</span>) * $size, $size),</span><br><span class="line">    <span class="string">&#x27;maxPage&#x27;</span> =&gt; $maxPage</span><br><span class="line">]);</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">page：获取用户端请求的页码值。</span></span><br><span class="line"><span class="comment">size：每页返回的记录数。</span></span><br><span class="line"><span class="comment">maxPage：计算总页数。</span></span><br><span class="line"><span class="comment">json_encode:返回“根据当前页码查询的记录”和“总页数”。</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">小李博客</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://xiaoliblog.cn">https://xiaoliblog.cn</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://xiaoliblog.cn" target="_blank">小李博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/JavaScript/">JavaScript</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/26/527e6ac3b16d4038ba3bd09e3b174450.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/wechat.png" target="_blank"><img class="post-qr-code-img" src="/img/wechat.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/img/alipay.png" target="_blank"><img class="post-qr-code-img" src="/img/alipay.png" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/page/js04.html"><img class="prev-cover" src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/26/527e6ac3b16d4038ba3bd09e3b174450.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">JavaScript🌞jQuery选择器及元素操作</div></div></a></div><div class="next-post pull-right"><a href="/page/js10.html"><img class="next-cover" src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/26/527e6ac3b16d4038ba3bd09e3b174450.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">JavaScript🌞正则表达式</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/page/js04.html" title="JavaScript🌞jQuery选择器及元素操作"><img class="cover" src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/26/527e6ac3b16d4038ba3bd09e3b174450.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-15</div><div class="title">JavaScript🌞jQuery选择器及元素操作</div></div></a></div><div><a href="/page/js06.html" title="JavaScript🌞函数"><img class="cover" src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/26/527e6ac3b16d4038ba3bd09e3b174450.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-15</div><div class="title">JavaScript🌞函数</div></div></a></div><div><a href="/page/js05.html" title="JavaScript🌞对象"><img class="cover" src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/26/527e6ac3b16d4038ba3bd09e3b174450.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-15</div><div class="title">JavaScript🌞对象</div></div></a></div><div><a href="/page/js08.html" title="JavaScript🌞数组"><img class="cover" src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/26/527e6ac3b16d4038ba3bd09e3b174450.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-15</div><div class="title">JavaScript🌞数组</div></div></a></div><div><a href="/page/js09.html" title="JavaScript🌞语法基础"><img class="cover" src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/26/527e6ac3b16d4038ba3bd09e3b174450.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-15</div><div class="title">JavaScript🌞语法基础</div></div></a></div><div><a href="/page/js02.html" title="JavaScript🌞BOM"><img class="cover" src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/26/527e6ac3b16d4038ba3bd09e3b174450.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-15</div><div class="title">JavaScript🌞BOM</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@6b5e7ef72be1c8973d94e5a9c49accbf775ad820/2021/02/01/c485da031fe0e464d04eaba8a66c4a8f.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">小李博客</div><div class="author-info__description">越努力，越幸运！</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">210</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">38</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">56</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xiaoliblog"><i class="fab fa-github"></i><span>博主的GitHub首页</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/xiaoliblog" target="_blank" title="Gitee"><i class="iconfont icon-gitee card_icon_gitee"></i></a><a class="social-icon" href="https://space.bilibili.com/390969485" target="_blank" title="BiliBili"><i class="iconfont icon-bilibili card_icon_bilibili"></i></a><a class="social-icon" href="http://wpa.qq.com/msgrd?v=3&amp;uin=2312057536&amp;site=CSDN&amp;menu=yes" target="_blank" title="QQ"><i class="iconfont icon-qq card_icon_qq"></i></a><a class="social-icon" href="https://github.com/xiaoliblog" target="_blank" title="GitHub"><i class="iconfont icon-git card_icon_git"></i></a><a class="social-icon" href="https://blog.csdn.net/qq_43266250?spm=1010.2135.3001.5113" target="_blank" title="CSDN"><i class="iconfont icon-csdn card_icon_csdn"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">正在考研备考中💦</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Ajax"><span class="toc-number">1.</span> <span class="toc-text">Ajax</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#PHP%E6%9C%8D%E5%8A%A1%E5%99%A8"><span class="toc-number">2.</span> <span class="toc-text">PHP服务器</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Ajax%E5%90%91%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%8F%91%E9%80%81%E8%AF%B7%E6%B1%82"><span class="toc-number">3.</span> <span class="toc-text">Ajax向服务器发送请求</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#GET%E8%AF%B7%E6%B1%82"><span class="toc-number">3.1.</span> <span class="toc-text">GET请求</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%A4%84%E7%90%86%E6%9C%8D%E5%8A%A1%E5%99%A8%E8%BF%94%E5%9B%9E%E7%9A%84%E4%BF%A1%E6%81%AF"><span class="toc-number">3.1.1.</span> <span class="toc-text">处理服务器返回的信息</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Post%E8%AF%B7%E6%B1%82"><span class="toc-number">3.2.</span> <span class="toc-text">Post请求</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%95%B0%E6%8D%AE%E4%BA%A4%E6%8D%A2%E6%A0%BC%E5%BC%8F"><span class="toc-number">4.</span> <span class="toc-text">数据交换格式</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%97%A0%E5%88%B7%E6%96%B0%E5%88%86%E9%A1%B5"><span class="toc-number">5.</span> <span class="toc-text">无刷新分页</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/page/project01.html" title="前端实例🥳响应式网站首页"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@c19917500ab083c77c7613263ba7ee74d5a08ae6/2021/04/30/469f30b141d73fa0fc4c962662d5813f.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="前端实例🥳响应式网站首页"/></a><div class="content"><a class="title" href="/page/project01.html" title="前端实例🥳响应式网站首页">前端实例🥳响应式网站首页</a><time datetime="2021-04-30T11:50:53.094Z" title="发表于 2021-04-30 19:50:53">2021-04-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/WeChatpay.html" title="微信支付对接"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@f2f670b92ea149650ffa7834354fc90284f2f44a/2021/04/29/5bdc9b381a06193d27cf2fb7c2fb608a.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="微信支付对接"/></a><div class="content"><a class="title" href="/page/WeChatpay.html" title="微信支付对接">微信支付对接</a><time datetime="2021-04-29T12:20:48.070Z" title="发表于 2021-04-29 20:20:48">2021-04-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/Alipay.html" title="支付宝支付对接"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@61a9b6a6e09e4bda38bb08e3104b717885beaee5/2021/04/29/c3fa51f9cf14e90d9e5a7aa8814dd041.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="支付宝支付对接"/></a><div class="content"><a class="title" href="/page/Alipay.html" title="支付宝支付对接">支付宝支付对接</a><time datetime="2021-04-27T16:00:00.000Z" title="发表于 2021-04-28 00:00:00">2021-04-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/Vuejs11.html" title="Vue.js前端框架🎯Pagination+PageHelper实现分页"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@61bf4245f6d84d2d0f66d163b89c916788cc1845/2021/04/13/ec6b232f8fe5a840e4bd8c3eabcf49b2.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="Vue.js前端框架🎯Pagination+PageHelper实现分页"/></a><div class="content"><a class="title" href="/page/Vuejs11.html" title="Vue.js前端框架🎯Pagination+PageHelper实现分页">Vue.js前端框架🎯Pagination+PageHelper实现分页</a><time datetime="2021-04-26T14:48:39.701Z" title="发表于 2021-04-26 22:48:39">2021-04-26</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/Vuejs10.html" title="Vue.js前端框架🎯Vue-Element-admin模版"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@61bf4245f6d84d2d0f66d163b89c916788cc1845/2021/04/13/ec6b232f8fe5a840e4bd8c3eabcf49b2.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="Vue.js前端框架🎯Vue-Element-admin模版"/></a><div class="content"><a class="title" href="/page/Vuejs10.html" title="Vue.js前端框架🎯Vue-Element-admin模版">Vue.js前端框架🎯Vue-Element-admin模版</a><time datetime="2021-04-19T16:00:00.000Z" title="发表于 2021-04-20 00:00:00">2021-04-20</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By 小李博客</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">🎯Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">🎉Butterfly</a></div><div class="footer_custom_text"><span><a style="margin-inline:5px" target="_blank" href="https://hexo.io/"><img src="https://img.shields.io/badge/Frame-Hexo-blue?style=flat&logo=hexo" title="博客框架为Hexo"></a><a style="margin-inline:5px" target="_blank" href="https://butterfly.js.org/"><img src="https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&logo=bitdefender" title="主题采用butterfly"></a><a style="margin-inline:5px" target="_blank" href="https://www.jsdelivr.com/"><img src="https://img.shields.io/badge/CDN-jsDelivr-orange?style=flat&logo=jsDelivr" title="本站使用JsDelivr为静态资源提供CDN加速"></a><a style="margin-inline:5px" target="_blank" href="https://vercel.com/ "><img src="https://img.shields.io/badge/Hosted-Vercel-brightgreen?style=flat&logo=Vercel" title="本站采用双线部署，默认线路托管于Vercel"></a><a style="margin-inline:5px" target="_blank" href="https://coding.net/ "><img src="https://img.shields.io/badge/Hosted-Coding-0cedbe?style=flat&logo=Codio" title="本站采用双线部署，联通线路托管于Coding"></a><a style="margin-inline:5px" target="_blank" href="https://github.com/"><img src="https://img.shields.io/badge/Source-Github-d021d6?style=flat&logo=GitHub" title="本站项目由Gtihub托管"></a><a style="margin-inline:5px" target="_blank" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img src="https://img.shields.io/badge/Copyright-BY--NC--SA%204.0-d42328?style=flat&logo=Claris" title="本站采用知识共享署名-非商业性使用-相同方式共享4.0国际许可协议进行许可"></a></span></div><div class="icp"><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/"><img class="icp-icon" src="/img/icp.png" alt="ICP"/><span>湘ICP备2021002541号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="rightside.chat_btn"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><div class="search-dialog__title" id="algolia-search-title">Algolia</div><div id="algolia-input-panel"><div id="algolia-search-input"></div></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-stats"></div></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script><script src="/js/main.js"></script><script defer src="/js/tw_cn.js"></script><script defer src="https://cdn.jsdelivr.net/npm/medium-zoom/dist/medium-zoom.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module" defer></script><script defer src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script defer src="/js/search/algolia.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    loader: {
      source: {
        '[tex]/amsCd': '[tex]/amscd'
      }
    },
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        addClass: [200,() => {
          document.querySelectorAll('mjx-container:not([display=\'true\']').forEach( node => {
            const target = node.parentNode
            if (!target.classList.contains('has-jax')) {
              target.classList.add('mathjax-overflow')
            }
          })
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script><script>(()=>{
  const $countDom = document.getElementById('twikoo-count')
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: 'xiaoliblog-8gj3j5045d5b0896',
      region: ''
    }, null))
  }

  const getCount = () => {
    twikoo.getCommentsCount({
      envId: 'xiaoliblog-8gj3j5045d5b0896',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      $countDom.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const loadTwikoo = (bool = false) => {
    if (typeof twikoo === 'object') {
      init()
      bool && $countDom && setTimeout(getCount,0)
    } else {
      getScript('https://cdn.jsdelivr.net/npm/twikoo@1.3.0/dist/twikoo.all.min.js').then(()=> {
        init()
        bool && $countDom && setTimeout(getCount,0)
      })
    }
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo(true)
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script defer src="//lib.baomitu.com/jquery/3.5.1/jquery.min.js"></script><script defer src="https://myhkw.cn/api/player/160561664166" id="myhk" key="160561664166" m="1"></script><div><canvas id="snow" style="position:fixed;top:0;left:0;width:100%;height:100%;z-index:99999;pointer-events:none"></canvas></div><script>const notMobile = (!(navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)));</script><scrip async type="text/javascript" src="https://cdn.jsdelivr.net/gh/Candinya/Kratos-Rebirth@latest/source/js/snow.min.js"></scrip><scrip defer src="https://cdn.jsdelivr.net/npm/hexo-theme-volantis@latest/source/js/issues.min.js"></scrip><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><script>var gitcalendar = new Vue({
  el: '#gitcalendar',
  data: {
    simplemode: true, 
    user: 'xiaoliblog',
    fixed: 'fixed',
    px: 'px',
    x: '',
    y: '',
    span1: '',
    span2: '',
    month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
    monthchange: [],
    oneyearbeforeday: '',
    thisday: '',
    amonthago: '',
    aweekago: '',
    weekdatacore: 0,
    datacore: 0,
    total: 0,
    datadate: '',
    data: [],
    positionplusdata: [],
    firstweek: [],
    lastweek: [],
    beforeweek: [],
    thisweekdatacore: 0,
    mounthbeforeday: 0,
    mounthfirstindex: 0,
    crispedges: 'crispedges',
    thisdayindex: 0,
    amonthagoindex: 0,
    amonthagoweek: [],
    firstdate: [],
    first2date: [],
    montharrbefore: [],
    monthindex: 0,
    color: ['#ebedf0', '#f1f8ff', '#dbedff', '#c8e1ff', '#79b8ff', '#2188ff', '#0366d6', '#005cc5', '#044289', '#032f62', '#05264c']
  },
  methods: {
    selectStyle(data, event) {
      document.querySelector('.angle-wrapper').style.display = 'block'
      this.span1 = data.date;
      this.span2 = data.count;
      this.x = event.clientX - 100;
      this.y = event.clientY - 60
    },
    outStyle() {
      document.querySelector('.angle-wrapper').style.display = 'none'
    },
    thiscolor(x) {
      if (x === 0) {
        let i = parseInt(x / 2);
        return this.color[0]
      } else if (x < 2) {
        return this.color[1]
      } else if (x < 20) {
        let i = parseInt(x / 2);
        return this.color[i]
      } else {
        return this.color[9]
      }
    },
  }
});
var apiurl = 'python-github-calendar-api-ruby.vercel.app' ? 'https://python-github-calendar-api-ruby.vercel.app/api?' : 'https://githubapi.ryanchristian.dev/user/'
var githubapiurl = apiurl + gitcalendar.user;
//canvas绘图
function responsiveChart() {
  let c = document.getElementById("gitcanvas");
  if (c) {
    let cmessage = document.getElementById("gitmessage");
    let ctx = c.getContext("2d");
    c.width = document.getElementById("gitcalendarcanvasbox").offsetWidth;
    let linemaxwitdh = 0.96 * c.width / gitcalendar.data.length;
    c.height = 9 * linemaxwitdh;
    let lineminwitdh = 0.8 * linemaxwitdh;
    let setposition = {
      x: 0.02 * c.width,
      y: 0.025 * c.width
    };
    for (let week in gitcalendar.data) {
      weekdata = gitcalendar.data[week];
      for (let day in weekdata) {
        let dataitem = {
          date: "",
          count: "",
          x: 0,
          y: 0
        };
        gitcalendar.positionplusdata.push(dataitem);
        ctx.fillStyle = gitcalendar.thiscolor(weekdata[day].count);
        setposition.y = Math.round(setposition.y * 100) / 100;
        dataitem.date = weekdata[day].date;
        dataitem.count = weekdata[day].count;
        dataitem.x = setposition.x;
        dataitem.y = setposition.y;
        ctx.fillRect(setposition.x, setposition.y, lineminwitdh, lineminwitdh);
        setposition.y = setposition.y + linemaxwitdh
      };
      setposition.y = 0.025 * c.width;
      setposition.x = setposition.x + linemaxwitdh
    };
    ctx.font = "600  Arial";
    ctx.fillStyle = '#aaa';
    ctx.fillText("日", 0, 1.9 * linemaxwitdh);
    ctx.fillText("二", 0, 3.9 * linemaxwitdh);
    ctx.fillText("四", 0, 5.9 * linemaxwitdh);
    ctx.fillText("六", 0, 7.9 * linemaxwitdh);
    let monthindexlist = c.width / 24;
    for (let index in gitcalendar.monthchange) {
      ctx.fillText(gitcalendar.monthchange[index], monthindexlist, 0.7 * linemaxwitdh);
      monthindexlist = monthindexlist + c.width / 12
    };
    cmessage.onmousemove = function(event) {
      document.querySelector('.angle-wrapper').style.display = 'none'
    };
    c.onmousemove = function(event) {
      document.querySelector('.angle-wrapper').style.display = 'none'
      getMousePos(c, event);
    };

    function getMousePos(canvas, event) {
      var rect = canvas.getBoundingClientRect();
      var x = event.clientX - rect.left * (canvas.width / rect.width);
      var y = event.clientY - rect.top * (canvas.height / rect.height);
      //console.log("x:"+x+",y:"+y);
      for (let item of gitcalendar.positionplusdata) {
        let lenthx = x - item.x;
        let lenthy = y - item.y;
        //console.log(lenthx,lenthy);
        if (0 < lenthx && lenthx < lineminwitdh) {
          if (0 < lenthy && lenthy < lineminwitdh) {
            //console.log(item.date,item.count)
            document.querySelector('.angle-wrapper').style.display = 'block'
            gitcalendar.span1 = item.date;
            gitcalendar.span2 = item.count;
            gitcalendar.x = event.clientX - 100;
            gitcalendar.y = event.clientY - 60
          }
        }
        //if(0< x - item.x <lineminwitdh&&0< y - item.y <lineminwitdh){
        //console.log(item.count,item.date);
        //}
      }
    }
  }
}
//数据统计算法
function addlastmonth() {
  if (gitcalendar.thisdayindex === 0) {
    thisweekcore(52);
    thisweekcore(51);
    thisweekcore(50);
    thisweekcore(49);
    thisweekcore(48);
    gitcalendar.thisweekdatacore += gitcalendar.firstdate[6].count;
    gitcalendar.amonthago = gitcalendar.firstdate[6].date
  } else {
    thisweekcore(52);
    thisweekcore(51);
    thisweekcore(50);
    thisweekcore(49);
    thisweek2core();
    gitcalendar.amonthago = gitcalendar.first2date[gitcalendar.thisdayindex - 1].date
  }
};

function thisweek2core() {
  for (let i = gitcalendar.thisdayindex - 1; i < gitcalendar.first2date.length; i++) {
    gitcalendar.thisweekdatacore += gitcalendar.first2date[i].count
  }
};

function thisweekcore(index) {
  for (let item of gitcalendar.data[index]) {
    gitcalendar.thisweekdatacore += item.count
  }
};

function addlastweek() {
  for (let item of gitcalendar.lastweek) {
    gitcalendar.weekdatacore += item.count
  }
};

function addbeforeweek() {
  for (let i = gitcalendar.thisdayindex; i < gitcalendar.beforeweek.length; i++) {
    gitcalendar.weekdatacore += gitcalendar.beforeweek[i].count
  }
};

function addweek(data) {
  if (gitcalendar.thisdayindex === 6) {
    gitcalendar.aweekago = gitcalendar.lastweek[0].date;
    addlastweek()
  } else {
    lastweek = data.contributions[51];
    gitcalendar.aweekago = lastweek[gitcalendar.thisdayindex + 1].date;
    addlastweek();
    addbeforeweek()
  }
}

fetch(githubapiurl)
  .then(data => data.json())
  .then(data => {
    gitcalendar.data = data.contributions;
    gitcalendar.total = data.total;
    gitcalendar.first2date = gitcalendar.data[48];
    gitcalendar.firstdate = gitcalendar.data[47];
    gitcalendar.firstweek = data.contributions[0];
    gitcalendar.lastweek = data.contributions[52];
    gitcalendar.beforeweek = data.contributions[51];
    gitcalendar.thisdayindex = gitcalendar.lastweek.length - 1;
    gitcalendar.thisday = gitcalendar.lastweek[gitcalendar.thisdayindex].date;
    gitcalendar.oneyearbeforeday = gitcalendar.firstweek[0].date;
    gitcalendar.monthindex = gitcalendar.thisday.substring(5, 7) * 1;
    gitcalendar.montharrbefore = gitcalendar.month.splice(gitcalendar.monthindex, 12 - gitcalendar.monthindex);
    gitcalendar.monthchange = gitcalendar.montharrbefore.concat(gitcalendar.month);
    addweek(data);
    addlastmonth();
    responsiveChart();
  })
  .catch(function(error) {
    console.log(error);
  });

//手机版更换为svg绘制
if (document.getElementById("gitcalendarcanvasbox").offsetWidth < 500) {
  gitcalendar.simplemode = false
}

//当改变窗口大小时重新绘制canvas
window.onresize = function() {
  if (gitcalendar.simplemode) responsiveChart()
}

//解决滚动滑轮时出现的标签显示
window.onscroll = function() {
  if (document.querySelector('.angle-wrapper')) {
    document.querySelector('.angle-wrapper').style.display = 'none'
  }
};</script></div><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"react":{"opacity":0.7}});</script></body></html>